<template>
  <div class="app-container editcss">
    <div class="dheight" v-loading="loadings" element-loading-text="查询中..." element-loading-spinner="el-icon-loading">
      <div class="titleHeight">
        <el-row>
          <el-col>
            <el-button type="primary" class="mb15 " size="small" icon="el-icon-plus"
              v-repeatStop="{ func: add, delay: '2000' }" style="float: left;margin-right: 10px;">
              新增
            </el-button>
            <screenSelect title="设备编码" type='input' v-model="queryFrom.equ_no" :isValue='queryFrom.equ_no'
              placeholder="请输入" @transfer="valueHeld($event, 'equ_no')" class=" mb15" width="200px"
              style="float: left;" />
            <screenSelect title="报警状态" type='select' v-model="queryFrom.is_warn" :isValue='queryFrom.is_warn'
              placeholder="请选择" @transfer="valueHeld($event, 'is_warn')" :options="equipmentstateoptions" class=" mb15"
              width="120px" style="float: left;" />
            <screenSelect title="所属企业" type='select' v-model="queryFrom.admin_id" :isValue='queryFrom.admin_id'
              placeholder="请选择" @transfer="valueHeld($event, 'admin_id')" :options="enterpriseoptions" class=" mb15"
              v-if="role == 1" width="200px" style="float: left;" />
            <screenSelect title="所属电站" type='select' v-model="queryFrom.base_station_id"
              :isValue='queryFrom.base_station_id' placeholder="请选择" @transfer="valueHeld($event, 'base_station_id')"
              :options="powerstationoptions" class=" mb15" width="200px" style="float: left;" />
            <screenSelect title="所属区域" type='select' v-model="queryFrom.region_id" :isValue='queryFrom.region_id'
              placeholder="请选择" @transfer="valueHeld($event, 'region_id')" :options="districtoptions" class=" mb15"
              width="200px" style="float: left;" />
            <screenSelect title="设备状态" type='select' v-model="queryFrom.status" :isValue='queryFrom.status'
              placeholder="请选择" @transfer="valueHeld($event, 'status')" :options="statusoptions" class=" mb15"
              width="120px" style="float: left;" />
            <screenSelect title="是否禁用" type='select' v-model="queryFrom.status_stop" :isValue='queryFrom.status_stop'
              placeholder="请选择" @transfer="valueHeld($event, 'status_stop')" :options="statusstopoptions" class=" mb15"
              width="120px" style="float: left;" />


          </el-col>

          <el-col>
            <div style="width: 174px;display: flex;float: left;">
              <el-button type="primary" class="mb15 " size="small" icon="el-icon-search"
                v-repeatStop="{ func: search, delay: '2000' }">
                搜索
              </el-button>
              <el-button type="primary" class="mb15 " size="small" icon="el-icon-refresh-left"
                v-repeatStop="{ func: reset, delay: '2000' }">
                重置
              </el-button>
            </div>
            <div style="width: 174px;float: left;display: flex;">
              <el-button type="primary" plain class="mb15" size="small"
                :disabled="multipleSelection.length == 0 ? true : false"
                v-repeatStop="{ func: operationtypeHeld, delay: '2000' }" icon="el-icon-plus"
                style="margin-right: 10px;">
                批量操作
              </el-button>
              <el-button type="danger" plain class="mb15" size="small"
                v-repeatStop="{ func: operationtypeHeldAll, delay: '2000' }" icon="el-icon-finished"
                style="margin-right: 10px;">
                全部操作
              </el-button>

            </div>

            <!-- <el-button type="warning" class="ch_button " :disabled="isDerive" @click="derive">
              <i class="el-icon-download"></i>
              <div>导入</div>
            </el-button>
            <el-button type="success" class="ch_button " :disabled="isDeriveout" @click="deriveout">
              <i class="el-icon-upload2"></i>
              <div>导出</div>
            </el-button> -->
          </el-col>

        </el-row>


      </div>
      <el-table :data="tableData" border style="width: 100%" :height="endHeight" v-loading="loading"
        element-loading-text="Loading..." element-loading-spinner="el-icon-loading"
        @selection-change="handleSelectionChange" :row-key="getRowkeys" ref="multipleTable">
        <el-table-column type="selection" width="55" :reserve-selection="true">
        </el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center">
        </el-table-column>
        <el-table-column label="设备编码" min-width="150" align="center">
          <template slot-scope="scope">
            {{ scope.row.equ_no }}
          </template>
        </el-table-column>
        <el-table-column label="所属区域" min-width="150" align="center">
          <template slot-scope="scope">
            {{ scope.row.region.name }}
          </template>
        </el-table-column>
        <el-table-column label="所属电站" min-width="150" align="center">
          <template slot-scope="scope">
            {{ scope.row.base_station.name }}
          </template>
        </el-table-column>
        <el-table-column label="设备状态/是否报警" min-width="100" align="center">
          <template slot-scope="scope">
            <div :style="scope.row.is_warn == 1 ? 'color:red;' : ''">{{ scope.row.status_name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="是否禁用" min-width="100" align="center">
          <template slot-scope="scope">
            <div :style="scope.row.status_stop == 0 ? 'color:red;' : ''">{{ scope.row.status_stop == 0 ? '禁用' : '启用' }}
            </div>
          </template>
        </el-table-column>

        <!-- <el-table-column label="使用时长" min-width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.equipmentduration }}
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="operation_box">
              <el-button @click.native.prevent="operationRow(scope.row)" type="text" class="operation_operation"
                size="mini">
                设备操作
              </el-button>
              <el-button @click.native.prevent="editRow(scope.row)" type="text" class="operation_edit" size="mini">
                编辑
              </el-button>
              <el-button @click.native.prevent="viewRow(scope.row)" type="text" class="operation_view" size="mini">
                查看
              </el-button>
              <!-- <el-button @click.native.prevent="deleteRow(scope.row)" type="text" class="operation_delete" size="mini" v-if="role==1">
                下架
              </el-button> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="paginationblock" v-if="total > 0">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pageData.page" :page-sizes="[10, 20, 30, 40]" :page-size="pageData.limit" :background="true"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
      <addequipment v-if="dialogFormVisible" :optionVal="addfrom" :enterpriseoptions="enterpriseoptions"
        :dialogFormVisible.sync="dialogFormVisible" @updata="cancel" @addupdata="addupdatasave"></addequipment>
      <viewequipment v-if="dialogViewVisible" :optionVal="addfrom" :dialogViewVisible.sync="dialogViewVisible"
        @viewHeld="viewHeld"></viewequipment>
      <operation :optionVal="addfromd" v-if="dialogOperationVisible"
        :dialogOperationVisible.sync="dialogOperationVisible" :operationtype="operationtype"
        :multipleSelection="multipleSelection" :idsall="idsall" :infoAll="infoAll" @OperationHeld="Operation">
      </operation>

    </div>
  </div>
</template>

<script>
import screenSelect from '@/components/screenSelect/index.vue';
import addequipment from './components/addequipment.vue';
import viewequipment from './components/viewequipment.vue';
import operation from './components/operation.vue';
import { getequList, addto, update, equbatchlist, getequshow, indelete } from '@/api/equipment.js'
import { getqiyeList, getDianzhanList, getquyuList } from '@/api/common.js'

export default {
  name: 'WorkspaceJsonEquipment',
  components: {
    screenSelect,
    addequipment,
    viewequipment,
    operation
  },
  data() {
    return {
      role: null,
      loading: true,
      loadings: false,
      isAll: false,
      operationtype: '0',
      dialogFormVisible: false,
      dialogViewVisible: false,
      dialogOperationVisible: false,
      isDerive: false,
      isDeriveout: false,
      queryFrom: {
        admin_id: '',
        base_station_id: '',
        region_id: '',
        equ_no: ''
      },
      endHeight: 0,
      pageData: {
        page: 1,
        limit: 10
      },
      total: 0,
      idsall: '',
      tableData: [],
      powerstationoptions: [],//企业
      districtoptions: [],//区域
      equipmentstateoptions: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '正常',
          value: 0
        },
        {
          label: '报警',
          value: 1
        },
      ],
      statusoptions: [
        {
          label: '正常',
          value: 1
        },
        {
          label: '停止',
          value: 2
        },
        {
          label: '离线',
          value: 4
        },
        {
          label: '检修',
          value: 5
        },
      ],
      statusstopoptions: [
        {
          label: '启用',
          value: 1
        },
        {
          label: '禁用',
          value: 0
        }
      ],
      enterpriseoptions: [],//电站
      addfrom: {},
      addfromd: {},
      multipleSelection: [],
      infoAll: {},
    };
  },
  watch: {
    'queryFrom.admin_id': {
      handler(newVal, oldVal) {
        if (newVal) {
          this.getDzList()
          this.queryFrom.region_id = ''
        }
      },
      deep: true,
      immediate: true
    },
    'queryFrom.base_station_id': {
      handler(newVal, oldVal) {
        if (newVal) {
          this.getQyList()
        }
      },
      deep: true,
      immediate: true
    },
  },
  mounted() {
    this.role = JSON.parse(localStorage.getItem('name')).role
    this.fetTableHeight()
    this.getList()
    this.getQiye()
    if (this.role != 1) {
      this.getDzList()
    }
  },

  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getDzList() {
      let data = {}
      data.type = 2
      if (this.role == 1) {
        data.id = this.queryFrom.admin_id
      } else {
        data.id = JSON.parse(localStorage.getItem('name')).admin_id
      }
      getDianzhanList(data).then(res => {
        if (res.code == 200) {
          res.data.map(item => {
            item.label = item.name
            item.value = item.id
          })
          this.powerstationoptions = res.data
          if (!this.powerstationoptions.some(x => { return x.id == this.queryFrom.base_station_id })) {
            this.queryFrom.base_station_id = ''
          }
        }
      })
    },
    getQyList() {
      let data = {}
      data.type = 3
      data.id = this.queryFrom.base_station_id
      getquyuList(data).then(res => {
        if (res.code == 200) {
          res.data.map(item => {
            item.label = item.name
            item.value = item.id
          })
          this.districtoptions = res.data
          if (!this.districtoptions.some(x => { return x.id == this.queryFrom.region_id })) {
            this.queryFrom.region_id = ''
          }
        }
      })
    },
    getQiye() {
      let that = this
      let data = {}
      data.type = 1
      getqiyeList(data).then(res => {
        if (res.code == 200) {
          res.data.map(item => {
            item.label = item.name
            item.value = item.id
          })
          that.enterpriseoptions = res.data
        }
      })
    },
    getList(data) {
      let that = this
      if (data) {
        getequList(data).then(res => {
          if (res.code == 200) {
            that.loading = false
            that.tableData = res.data.rows
            console.log(that.tableData, '数据');
            that.total = res.data.count
          }
        })
      } else {
        getequList(that.pageData).then(res => {
          if (res.code == 200) {
            that.loading = false
            that.tableData = res.data.rows
            console.log(that.tableData, '数据');
            that.total = res.data.count
          }
        })
      }

    },
    cancel(e) {
      this.dialogFormVisible = e.dialogFormVisible
      this.addfrom = e.form
    },
    addupdatasave(e) {
      console.log(e.form);
      let that = this
      if (e.form.id) {
        update(e.form).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess(res.message)
            this.dialogFormVisible = e.dialogFormVisible
            this.getList()
          } else {
            that.$modal.msgError(res.message)
          }
        })
      } else {
        addto(e.form).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess(res.message)
            this.dialogFormVisible = e.dialogFormVisible
            this.getList()
          } else {
            that.$modal.msgError(res.message)
          }
        })
      }
    },
    add() {
      this.addfrom = {
        admin_id: '',
        base_station_id: ''
      }
      this.dialogFormVisible = true
    },
    operationtypeHeld() {
      this.operationtype = '1'
      this.dialogOperationVisible = true
    },
    //return 信息
    infoRetrn(data, id) {
      let str = ''
      if (data.length != 0) {
        data.map(item => {
          if (item.id == id) {
            str = item.name
          }
        })
      }
      return str
    },
    operationtypeHeldAll() {
      this.operationtype = '1'
      if (this.queryFrom.admin_id == '' && this.role == 1) {
        return this.$Toast('请先选择企业')
      }
      console.log(this.isAll);

      if (this.isAll) {
        return this.$Toast('请先搜索')
      }
      let dataAll = {}
      if (this.queryFrom.admin_id) {
        dataAll.admin_id = this.queryFrom.admin_id
        dataAll.admin_name = this.infoRetrn(this.enterpriseoptions, this.queryFrom.admin_id)
      }
      if (this.queryFrom.base_station_id && this.queryFrom.base_station_id != '') {
        dataAll.base_station_id = this.queryFrom.base_station_id
        dataAll.base_station_name = this.infoRetrn(this.powerstationoptions, this.queryFrom.base_station_id)
      }
      if (this.queryFrom.region_id && this.queryFrom.region_id != '') {
        dataAll.region_id = this.queryFrom.region_id
        dataAll.region_name = this.infoRetrn(this.districtoptions, this.queryFrom.region_id)
      }
      this.infoAll = dataAll
      console.log(this.infoAll);

      // return
      equbatchlist(this.queryFrom).then(res => {
        console.log(res.data);
        if (res.code == 200) {
          this.dialogOperationVisible = true
          this.idsall = res.data
        }
      })
    },

    editRow(row) {
      this.addfrom = JSON.parse(JSON.stringify(row))
      console.log(this.addfrom);
      this.dialogFormVisible = true
    },
    viewHeld(e) {
      this.dialogViewVisible = e
    },
    Operation(e) {

      if (e == 'a') {
        this.loading = true
        let data = this.mergeObjects(this.pageData, this.queryFrom)
        this.getList(data)
        this.dialogOperationVisible = false
      } else {
        this.dialogOperationVisible = e
      }

    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    operationRow(row) {
      let status = JSON.parse(JSON.stringify(row)).status
      if (status == 1) {
        let id = JSON.parse(JSON.stringify(row)).id
        let data = {}
        data.id = id
        this.loadings = true
        getequshow(data).then(res => {
          if (res.code == 200) {
            this.addfromd = JSON.parse(JSON.stringify(res.data))
            this.loadings = false
            this.operationtype = '0'
            this.toggleSelection()
            this.dialogOperationVisible = true
          } else {
            this.$modal.msgSuccess(res.message)
          }
        })
      } else {
        this.$modal.msgError('设备非在线不可操作！')
      }


    },
    viewRow(row) {
      this.addfrom = JSON.parse(JSON.stringify(row))
      this.dialogViewVisible = true
      console.log(row, '查看');
    },
    deleteRow(row) {
      this.$confirm('此操作将下架' + row.equ_no + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: false,
      }).then(() => {
        let data = {}
        data.id = row.id
        indelete(data).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess(res.message)
            this.loading = true
            this.getList()
          } else {
            this.$modal.msgError(res.message)
          }
        })
      }).catch(() => {
        this.$modal.msg('已取消下架')
      });
    },
    search() {
      this.pageData = {
        page: 1,
        limit: 10
      }
      this.isAll = false
      this.loading = true
      let data = this.mergeObjects(this.pageData, this.queryFrom)
      this.getList(data)
      console.log(this.queryFrom);
    },
    reset() {
      this.queryFrom = {
        admin_id: '',
        base_station_id: '',
        region_id: '',
        equ_no: ''
      }
    },
    mergeObjects(obj1, obj2) {
      return Object.assign({}, obj1, obj2);
    },
    //导入
    derive() {
      this.isDerive = true
      // getTimeExpor(this.queryFrom).then(res => {
      //   const link = document.createElement('a')
      //   const blob = new Blob([res.data], {
      //     type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      //   })
      //   console.log(res);
      //   const fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1].substring(7));
      //   link.setAttribute('download', fileName)
      //   link.style.display = 'none'
      //   link.href = URL.createObjectURL(blob)
      //   link.click()
      //   setTimeout(() => {
      //     this.isDerive = false
      //   }, 5000)
      // }).catch(err => {
      //   setTimeout(() => {
      //     this.isDerive = false
      //   }, 5000)
      // })
      setTimeout(() => {
        this.isDerive = false
      }, 5000)
    },
    //导出
    deriveout() {
      this.isDeriveout = true
      // getTimeExpor(this.queryFrom).then(res => {
      //   const link = document.createElement('a')
      //   const blob = new Blob([res.data], {
      //     type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      //   })
      //   console.log(res);
      //   const fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1].substring(7));
      //   link.setAttribute('download', fileName)
      //   link.style.display = 'none'
      //   link.href = URL.createObjectURL(blob)
      //   link.click()
      //   setTimeout(() => {
      //     this.isDerive = false
      //   }, 5000)
      // }).catch(err => {
      //   setTimeout(() => {
      //     this.isDerive = false
      //   }, 5000)
      // })
      setTimeout(() => {
        this.isDeriveout = false
      }, 5000)
    },
    resetHeight() {
      return new Promise((resolve, reject) => {
        this.endHeight = 0
        resolve()
      })
    },
    fetTableHeight() {
      this.resetHeight().then(res => {
        let fHeight = (window.getComputedStyle(document.querySelector('.editcss')).height).replace('px', "")
        let zHeight = (window.getComputedStyle(document.querySelector('.titleHeight')).height).replace('px', "")
        this.endHeight = (fHeight - zHeight - 92)
      })
    },
    handleSizeChange(val) {
      this.pageData.limit = val

      this.loading = true
      let data = this.mergeObjects(this.pageData, this.queryFrom)
      this.getList(data)
    },
    handleCurrentChange(val) {
      this.pageData.page = val

      this.loading = true
      let data = this.mergeObjects(this.pageData, this.queryFrom)
      this.getList(data)
    },
    getRowkeys(row){
    return row.id

    },
    valueHeld(childParam, fatherparam) {
      this.queryFrom[fatherparam] = childParam
      this.isAll = childParam == '' ? false : true
    },
  },
};
</script>

<style lang="scss" scoped>
.dheight {
  // box-shadow: 0 0 10px #BBBBBB;
  border-radius: 6px;
  // padding: 20px;
  height: calc(100%);
  position: relative;
}

::v-deep .el-button.ch_button {
  padding: 7px 9px;
}

::v-deep .el-button.ch_button span {
  display: flex;
  align-items: center;

  i {
    font-size: 16px;
  }

  div {
    font-size: 13px;
    font-weight: 400;
    margin-left: 4px;
  }
}
</style>